<template>
  <div
    style="width: 100%; height: 100%; overflow-x: hidden; overflow-y: hidden"
  >
    <div class="list-card">
      <div class="top-nav">
        <div>
          <el-button
            @click="lastPage"
            size="mini"
            :disabled="currentPage <= 0"
            :icon="ArrowLeftBold"
            title="返回"
          ></el-button>
          <!-- <el-button
          @click="nextPage"
          size="mini"
          :disabled="pathArray.length - 1 == currentPage"
          :icon="ArrowRightBold"
        ></el-button> -->
          <el-button
            @click="onLoad"
            size="mini"
            :icon="Refresh"
            title="刷新"
          ></el-button>
          <el-button
            @click="create('file')"
            size="mini"
            :icon="DocumentAdd"
            title="新建文件"
          ></el-button>
          <el-button
            @click="create('dir')"
            size="mini"
            :icon="FolderAdd"
            title="新建文件夹"
          ></el-button>
          <div style="display: inline-block; padding-left: 10px; width: 275px">
            <el-input
              v-model="inputDir"
              size="mini"
              placeholder="请输入目录名"
              :prefix-icon="Files"
            >
              <template #append>
                <el-button
                  :icon="Right"
                  size="mini"
                  title="进入目录"
                  @click="toDir"
                ></el-button>
              </template>
            </el-input>
          </div>
        </div>
        <div style="display: flex; align-items: center">
          <div style="display: inline-block; padding-right: 15px">
            <el-avatar
              :size="28"
              :src="circleUrl"
              :title="username"
            ></el-avatar>
          </div>
          <div style="display: inline-block; padding-right: 10px">
            <el-dropdown>
              <span class="el-dropdown-link">
                {{ username }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    @click="toPageUser"
                    v-if="usertype === 'ADMIN' || usertype === 'MANAGER'"
                  >
                    用户管理</el-dropdown-item
                  >
                  <el-dropdown-item
                    :divided="usertype === 'ADMIN' || usertype === 'MANAGER'"
                    @click="logout"
                    >退出系统</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      <el-table
        :data="tableData"
        height="600"
        style="width: 100%"
        v-loading="loading"
        @cell-click="clickFile"
      >
        <el-table-column prop="name" label="文件名" width="300px">
          <template #default="scope">
            <div class="flex-center content-can-click">
              <!-- <el-image style="width: 16px; height: 16px" :src="url"></el-image> -->
              <Icon :isDir="scope.row.is_dir" :ext="scope.row.ext"></Icon>
              <span
                class="file-name"
                style="padding-left: 10px"
                :title="scope.row.name"
                >{{ scope.row.name }}</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="size" sortable label="文件大小">
          <template #default="scope">
            <span>{{
              scope.row.is_dir
                ? ""
                : scope.row.size < 1024
                ? scope.row.size + "B"
                : scope.row.size < 1024 * 1024
                ? parseInt(scope.row.size / 1024) + "KB"
                : parseInt(scope.row.size / 1024 / 1024) + "MB"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="time" sortable label="上次修改时间" />
        <el-table-column fixed="right" label="操作" width="125">
          <template #default="scope">
            <el-button
              size="mini"
              type="primary"
              title="编辑"
              @click="handleEdit(scope.$index, scope.row)"
              :icon="Edit"
            ></el-button>
            <!-- <el-button
            size="mini"
            type="success"
            @click="download(scope.$index, scope.row)"
            :icon="Download"
          ></el-button> -->
            <el-button
              size="mini"
              type="danger"
              title="删除"
              @click="handleDelete(scope.$index, scope.row)"
              :icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="outerVisible" :title="writeTitle">
      <template #default>
        <el-input
          v-model="textarea"
          :rows="10"
          type="textarea"
          placeholder="请输入内容"
      /></template>
      <template #title>
        <div class="flex-center">
          <Icon :isDir="writeIsDir" :ext="writeExt"></Icon>
          <span
            class="file-name"
            style="padding-left: 5px"
            :title="writeTitle"
            >{{ writeTitle }}</span
          >
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outerVisible = false">取消</el-button>
          <el-button type="primary" @click="writeFile">修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style></style>
<script setup>
import { ref, reactive, onMounted } from "vue"
import { ElMessageBox, ElMessage } from "element-plus"

import {
  Search,
  Edit,
  Check,
  Message,
  Star,
  Delete,
  ArrowLeftBold,
  ArrowRightBold,
  Refresh,
  Download,
  DocumentAdd,
  FolderAdd,
  Files,
  Right,
  ArrowDown,
} from "@element-plus/icons-vue"

import qs from "qs"
import Icon from "@/components/Icon.vue"

const PATH = "D:\\file"

const form = reactive({
  path: PATH,
})

const pathArray = ref([
  {
    path: PATH,
    is_selected: true,
  },
])

const username = ref("")
const usertype = ref("")

const EXT_CAN_OPEN = [
  ".txt",
  ".conf",
  ".ini",
  ".config",
  ".py",
  ".java",
  ".html",
  ".css",
  ".js",
  ".php",
  ".go",
  ".c",
  ".cpp",
  ".vue",
  ".md",
  ".json",
  ".cs",
  ".jsx",
]

const url = ref("src/assets/icon/file.png")

const inputDir = ref(PATH)

import { useRouter, useRoute } from "vue-router"
const route = useRoute()
const router = useRouter()

const currentPage = ref(0)
const currentPath = ref("")

const loading = ref(false)

const tableData = ref([])
const lastData = ref([])
const BASE_URL = import.meta.env.VITE_API_BASE_URL

const outerVisible = ref(false)

const textarea = ref("")

const writeTitle = ref("")
const writeIsDir = ref(false)
const writeExt = ref("")

const circleUrl = ref(
  "https://image.windstormlab.com/img/ddb5987315caa3830a292164df0a02fb@478x476.jpg"
)

const dealData = (data) => {
  let length = data.length
  let dirArr = []
  let fileArr = []
  for (let i = 0; i < length; i++) {
    if (data[i].is_dir) {
      dirArr.push(data[i])
    } else {
      fileArr.push(data[i])
    }
  }
  return dirArr.concat(fileArr)
}

const onLoad = (type) => {
  lastData.value = tableData.value
  tableData.value = []
  loading.value = true
  fetch(`${BASE_URL}/file/list`, {
    method: "POST",
    mode: "cors",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Token: localStorage.getItem("token"),
    },
    body: qs.stringify(form),
  })
    .then((response) => {
      return response.json()
    })
    .then((res) => {
      loading.value = false
      if (res.code == 0) {
        if (type === "newPage" || type === "toPage") {
          dealPage()
        }
        currentPath.value = form.path
        inputDir.value = form.path
        tableData.value = dealData(res.data)
      } else {
        if (type === "toPage") {
          inputDir.value = currentPath.value
        }
        tableData.value = lastData.value
        ElMessage({
          message: res.msg,
          type: "warning",
        })
      }
    })
    .catch((err) => {
      loading.value = false
      tableData.value = lastData.value
      ElMessage({
        message: err,
        type: "warning",
      })
    })
}

const reset = () => {
  for (let i = 0; i < pathArray.value.length; i++) {
    pathArray.value[i].is_selected = false
  }
}

const loadPage = (path, type) => {
  form.path = path
  onLoad(type)
}

const dealPage = () => {
  reset()
  pathArray.value.push({
    path: form.path,
    is_selected: true,
  })
  currentPage.value++
}

const readFile = (path) => {
  loading.value = true
  fetch(`${BASE_URL}/file/read`, {
    method: "POST",
    mode: "cors",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Token: localStorage.getItem("token"),
    },
    body: qs.stringify({
      path: path,
    }),
  })
    .then((response) => {
      return response.json()
    })
    .then((res) => {
      loading.value = false
      if (res.code == 0) {
        textarea.value = res.data.content
        outerVisible.value = true
      } else {
        ElMessage({
          message: res.msg,
          type: "warning",
        })
      }
    })
    .catch((error) => {
      ElMessage({
        message: error,
        type: "error",
      })
    })
}

const create = (type) => {
  if (type == "dir" || type == "file") {
    let option = "createFile"
    if (type == "dir") {
      option = "createDir"
    }
    let title = "新建文件"
    if (type == "dir") {
      title = "新建文件夹"
    }
    let tips = "请输入新建的文件名"
    if (type == "dir") {
      tips = "请输入新建的目录名"
    }
    ElMessageBox.prompt(tips, title, {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    })
      .then(({ value }) => {
        if (value !== "") {
          let currentDir = ""
          if (
            currentDir.substr(currentDir.length - 1, 1) == "\\" ||
            currentDir.substr(currentDir.length - 1, 1) == "/"
          ) {
            currentDir = form.path
          } else {
            currentDir = form.path + "\\"
          }

          loading.value = true
          fetch(`${BASE_URL}/file/${option}`, {
            method: "POST",
            mode: "cors",
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              Token: localStorage.getItem("token"),
            },
            body: qs.stringify({
              path: currentDir + value,
            }),
          })
            .then((response) => {
              return response.json()
            })
            .then((res) => {
              loading.value = false
              if (res.code == 0) {
                onLoad()
                ElMessage({
                  message: "新建成功",
                  type: "success",
                })
              } else {
                ElMessage({
                  message: res.msg,
                  type: "warning",
                })
              }
            })
            .catch((error) => {
              ElMessage({
                message: error,
                type: "error",
              })
            })
        } else {
          ElMessage({
            message: "请输入内容",
            type: "warning",
          })
        }
      })
      .catch(() => {})
  }
}

const writeFile = () => {
  loading.value = true
  outerVisible.value = false

  fetch(`${BASE_URL}/file/write`, {
    method: "POST",
    mode: "cors",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Token: localStorage.getItem("token"),
    },
    body: qs.stringify({
      path: currentPath.value,
      content: textarea.value,
    }),
  })
    .then((response) => {
      return response.json()
    })
    .then((res) => {
      loading.value = false
      if (res.code == 0) {
        onLoad()
        ElMessage({
          message: "文件内容修改成功",
          type: "success",
        })
      } else {
        ElMessage({
          message: res.msg,
          type: "warning",
        })
      }
    })
    .catch((error) => {
      ElMessage({
        message: error,
        type: "error",
      })
    })
}

const clickFile = (row, column, cell, event) => {
  //   console.log(row, column, cell, event)
  if (column.label !== "操作") {
    if (row.is_dir) {
      loadPage(row.path, "newPage")
    } else {
      if (EXT_CAN_OPEN.indexOf(row.ext) >= 0) {
        writeTitle.value = row.name
        writeIsDir.value = row.is_dir
        writeExt.value = row.ext
        currentPath.value = row.path
        readFile(row.path)
      } else {
        ElMessage({
          message: "该类型文件暂不支持查看",
          type: "warning",
        })
      }
    }
  }
}

const lastPage = () => {
  let newPage = currentPage.value - 1
  if (newPage >= 0) {
    pathArray.value.splice(pathArray.value.length - 1, 1)
    currentPage.value = newPage
    reset()
    pathArray.value[newPage].is_selected = true
    loadPage(pathArray.value[newPage].path)
  } else {
    ElMessage({
      message: "没有上一页",
      type: "warning",
    })
  }
}

// const nextPage = () => {
//   let newPage = currentPage.value + 1
//   if (pathArray.value.length > newPage) {
//     currentPage.value = newPage
//     reset()
//     pathArray.value[newPage].is_selected = true
//     loadPage(pathArray.value[newPage].path)
//   } else {
//     ElMessage({
//       message: "没有下一页",
//       type: "warning",
//     })
//   }
// }

const download = (index, row) => {
  console.log(index, row)
  if (!row.is_dir) {
    window.open(row.path)
  }
}

const handleEdit = (index, row) => {
  let name = row.name
  ElMessageBox.prompt("重命名文件或文件夹", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputValue: name,
  })
    .then(({ value }) => {
      if (value !== "") {
        loading.value = true
        fetch(`${BASE_URL}/file/rename`, {
          method: "POST",
          mode: "cors",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Token: localStorage.getItem("token"),
          },
          body: qs.stringify({
            path: form.path,
            old_name: name,
            new_name: value,
          }),
        })
          .then((response) => {
            return response.json()
          })
          .then((res) => {
            loading.value = false
            if (res.code == 0) {
              onLoad()
              ElMessage({
                message: "修改成功",
                type: "success",
              })
            } else {
              ElMessage({
                message: res.msg,
                type: "warning",
              })
            }
          })
          .catch((error) => {
            ElMessage({
              message: error,
              type: "error",
            })
          })
      } else {
        ElMessage({
          message: "请输入内容",
          type: "warning",
        })
      }
    })
    .catch(() => {})
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm("是否确认删除该文件？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true
      fetch(`${BASE_URL}/file/remove`, {
        method: "POST",
        mode: "cors",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Token: localStorage.getItem("token"),
        },
        body: qs.stringify({
          path: row.path,
        }),
      })
        .then((response) => {
          return response.json()
        })
        .then((res) => {
          loading.value = false
          if (res.code == 0) {
            onLoad()
            ElMessage({
              message: "删除成功",
              type: "success",
            })
          } else {
            ElMessage({
              message: res.msg,
              type: "warning",
            })
          }
        })
        .catch((error) => {
          ElMessage({
            message: error,
            type: "error",
          })
        })
    })
    .catch(() => {})
}

const logout = () => {
  ElMessageBox.confirm("确认退出后将清除登录记录", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true
      localStorage.removeItem("token")
      localStorage.removeItem("username")
      setTimeout(() => {
        loading.value = false
        router.replace({
          path: "/",
        })
      }, 1000)
    })
    .catch(() => {})
}

const toDir = () => {
  let dir = inputDir.value
  let currentDir = form.path
  if (dir != "" && dir != currentDir) {
    loadPage(dir, "toPage")
  }
}

const toPageUser = () => {
  router.push({
    path: "/user",
  })
}

onMounted(() => {
  username.value = localStorage.getItem("username") || "Unknown"
  usertype.value = localStorage.getItem("usertype") || "GUEST"
  onLoad()
})
</script>
